package com.finley.flowabledemo.design.state.demo02.state;


import cn.hutool.core.util.StrUtil;
import com.finley.flowabledemo.design.state.demo02.source.*;

/**
 * @description:
 * @author: xianfei.chao
 * @date 2025/6/24 17:21
 * @version: 1.0
 */
public class PaidStatueState extends OrderStatusState {


    @Override
    void handle(OrderStatusContext orderStatusContext) {
        Order order = orderStatusContext.getOrder();
        if (StrUtil.equalsIgnoreCase(order.getStatus(), OrderStatus.PROCESSING.getCode())) {
            DatabaseConnection2 conn = orderStatusContext.getConn();
            PaymentProcessor paymentProcessor = new PaymentProcessor();
            boolean paymentResult = paymentProcessor.processPayment(order.getPaymentDetails(), order.getTotalAmount());
            if (paymentResult) {
                conn.executeUpdate("UPDATE orders SET status='PAID' WHERE id=" + order.getId());
                for (OrderItem item : order.getItems()) {
                    conn.executeUpdate("UPDATE inventory SET quantity=quantity-" + item.getQuantity() + " WHERE product_id=" + item.getProductId());
                }
            }
        } else {
            orderStatusContext.setOrderStatusState(new ShippedStatusState());
            orderStatusContext.execHandler();
        }
    }
}
